<template>
  <div style="width: 100%; height: 100%; background: #fff; border-radius: 10px">
    <el-tabs
      style="padding: 0 0 16px 28px"
      v-model="activeName"
      @tab-click="handleClick"
    >
      <el-tab-pane label="学会介绍" name="学会介绍">
        <div class="col center">
          <div style="width: 90%">
            <edit_articleVue :type="introductionType" ref="introduction" />
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="现任领导" name="现任领导">
        <el-button type="primary" @click="addLeader">新增</el-button>
        <el-row style="width: 100%">
          <el-card
            :body-style="{ padding: '0px' }"
            class="card"
            v-for="item in leaderList"
            :key="item.id"
          >
            <div
              class="col"
              style="
                align-items: center;
                justify-content: space-between;
                padding: 8px;
              "
            >
              <el-text truncated style="width: 100%">{{ item.header }}</el-text>
              <div class="col center" style="height: 160px">
                <el-image :src="item.url" fit="fill" />
              </div>
              <el-text truncated style="width: 100%">{{ item.footer }}</el-text>
              <div class="bottom">
                <el-button
                  text
                  class="button"
                  style="color: blue"
                  @click="editLeader(item)"
                  >修改</el-button
                >
                <el-button
                  text
                  class="button"
                  style="color: red"
                  @click="deleteLeader(item.id)"
                  >删除{{ item.id }}</el-button
                >
              </div>
            </div>
          </el-card>
        </el-row>
        <el-dialog
          v-model="isDialogVisible"
          class="col"
          style="align-items: center; width: 480px"
          title="新增领导"
        >
          <el-form
            ref="ruleFormRef"
            :model="leader"
            status-icon
            :rules="rules"
            label-width="80px"
            style="width: 300px"
          >
            <el-form-item label="顶部描述" prop="header">
              <el-input v-model="leader.header" autocomplete="off" />
            </el-form-item>
            <el-form-item label="上传照片">
              <el-upload
                class="avatar-uploader"
                style="width: 100%"
                :auto-upload="false"
                :show-file-list="false"
                v-model:file-list="fileList"
              >
                <img
                  style="width: 100%; height: auto"
                  v-if="leader.url"
                  :src="leader.url"
                />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>

            <el-form-item label="顶部描述" prop="header">
              <el-input v-model="leader.footer" autocomplete="off" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span>
              <el-button type="primary" @click="saveLeader"> 保存 </el-button>
              <el-button @click="isDialogVisible = false">取消</el-button>
            </span>
          </template>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="研究会章程" name="研究会章程">
        <div class="col center">
          <div style="width: 90%">
            <edit_articleVue :type="rulesType" ref="rules" />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts" setup>
import axios from 'axios'
import { onBeforeUnmount, onMounted, ref, nextTick, watch } from 'vue'
import edit_articleVue from './edit_article.vue'
import {
  ElMessage,
  ElMessageBox,
  TabsPaneContext,
  UploadUserFile,
} from 'element-plus'
const activeName = ref('学会介绍')
const introductionType = ref('add')
const rulesType = ref('add')
const introduction = ref<InstanceType<typeof edit_articleVue>>()
const rules = ref<InstanceType<typeof edit_articleVue>>()
const introductionData = ref()
const rulesData = ref()
const isDialogVisible = ref(false)
const isAddLeader = ref(false)
const fileList = ref<UploadUserFile[]>([]) //文件列表
const leader = ref({
  id: '',
  header: '',
  url: '',
  footer: '',
})
const leaderList = ref<any>([])

const getIntroduction = () => {
  axios
    .get('/api/getEssayByType', {
      headers: {
        Authorization: `Bearer ${window.localStorage.getItem('token')}`,
      },
      params: {
        type: '学会介绍',
      },
    })
    .then((res) => {
      introductionData.value = res.data.data[0]
      introductionType.value = 'edit'
      introduction.value?.setArticle(introductionData.value)
    })
}

const getRules = () => {
  axios
    .get('/api/getEssayByType', {
      headers: {
        Authorization: `Bearer ${window.localStorage.getItem('token')}`,
      },
      params: {
        type: '研究会章程',
      },
    })
    .then((res) => {
      rulesData.value = res.data.data[0]
      rulesType.value = 'edit'
      rules.value?.setArticle(rulesData.value)
    })
}

const getAllLeader = () => {
  axios.get('/api/getAllLeader').then((res) => {
    leaderList.value = res.data.data
    console.log(res)
  })
}

onMounted(() => {
  getIntroduction()
  getRules()
  getAllLeader()
})

onBeforeUnmount(() => {
  if (introduction.value?.haveChange) {
    introduction.value?.save()
  }
  if (rules.value?.haveChange) {
    rules.value?.save()
  }
})

const handleClick = (tab: TabsPaneContext) => {
  if (activeName.value === '学会介绍' && tab.paneName != '学会介绍') {
    if (introduction.value?.haveChange) {
      introduction.value?.save()
    }
  }
  if (activeName.value === '研究会章程' && tab.paneName != '研究会章程') {
    if (rules.value?.haveChange) {
      rules.value?.save()
    }
  }
}

// 添加领导
const addLeader = () => {
  leader.value = {
    id: '',
    header: '',
    url: '',
    footer: '',
  }
  isAddLeader.value = true
  isDialogVisible.value = true
}

// 上传文件
const submitUpload = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('未选择文件')
    return false
  }
  console.log(fileList.value)

  await axios({
    url: 'http://119.29.216.71:35802/api/upload',
    method: 'post',
    data: {
      upload: fileList.value[0].raw,
    },
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
    .then((res) => {
      fileList.value[0].url = res.data.data.url
      leader.value.url = res.data.data.url
    })
    .catch(() => {
      ElMessage.error('上传失败')
      return false
    })

  ElMessage.success('上传成功')
  return true
}
watch(fileList, () => {
  if (fileList.value.length === 2) {
    fileList.value.shift()
  }
  submitUpload()
})

// 编辑领导
const editLeader = (paramLeader: any) => {
  isAddLeader.value = false
  isDialogVisible.value = true
  console.log(paramLeader)

  nextTick(() => {
    leader.value.id = paramLeader.id
    leader.value.header = paramLeader.header
    leader.value.url = paramLeader.url
    leader.value.footer = paramLeader.footer
  })
}
// 删除领导
const deleteLeader = (id: any) => {
  ElMessageBox.confirm('你确定要删除该领导吗？此操作不可逆', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axios
        .delete('/api/delLeader', {
          data: {
            id: parseInt(id),
          },
        })
        .then(() => {
          getAllLeader()
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        })
        .catch(() => {
          ElMessage({
            type: 'error',
            message: '删除失败',
          })
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 保存领导
const saveLeader = async () => {
  if (isAddLeader.value) {
    axios
      .post('/api/addLeader', {
        header: leader.value.header,
        url: leader.value.url,
        footer: leader.value.footer,
      })
      .then(() => {
        ElMessage.success('添加成功')
        getAllLeader()

        isDialogVisible.value = false
      })
      .catch(() => {
        ElMessage.error('添加失败')
      })
  } else {
    console.log(leader.value)
    axios
      .put('/api/updateLeaderInfo', {
        id: leader.value.id,
        header: leader.value.header,
        url: leader.value.url,
        footer: leader.value.footer,
      })
      .then(() => {
        ElMessage.success('修改成功')
        getAllLeader()
        isDialogVisible.value = false
      })
      .catch(() => {
        ElMessage.error('修改失败')
      })
  }
  getAllLeader()
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.card {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  width: 250px;
  height: 260px;
  margin: 12px;
  padding: 0px;
}
</style>
